import datetime
import time

from afast_core.core_tools import random_helper
from afast_core.core_tools.snow_flake_helper import Snow
from infirmary_admin_src.infirmary_common.infirmary_controller import IBaseController
from infirmary_admin_src.infirmary_common.infirmary_controller.rest_controller_with_depends import \
    RestControllerWithDepends
from fastapi import Request, Depends, Path, Body

from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.infirmary.businesses.schemas import SchemaBase
from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.infirmary.businesses.services.service_businesses import \
    Businesses
from infirmary_admin_src.infirmary_smart_admin.infirmary_utils import generate_time_array_for_times, weekdaystrftime



class XParam(SchemaBase):
    '''
    账号密码登录参数
    '''
    appid: str= None
    dc_number: str= None
    si_number: str= None
    scheduling_dnotime: str = None
    scheduling_ampm: str = None

    # =============
    interval_am_sart:str = None
    interval_am_end:str = None
    interval_pm_sart:str = None
    interval_pm_end:str = None
    interval_scheduling_stock: int
    interval_time: int




class IController(IBaseController):
    '''
    定制相关约束检测函数逻辑步序
    '''

    def __init__(self, *, request: Request,
                 schema_param: XParam,
                 ):
        super().__init__(request=request)
        # 入参参数
        # 入参参数
        self.schema_param = schema_param


import re
def is_valid_time_format(string):
    # 字符串格必须是时间格式的 00：00
    pattern = r'^\d{2}:\d{2}$'
    match = re.match(pattern, string)
    if match:
        return True
    else:
        return False

def is_valid_time_format_riqi(string):
    # 字符串必须是日期格式的 YYYY-MM-DD
    pattern = r'^\d{4}-\d{2}-\d{2}$'
    match = re.match(pattern, string)
    if match:
        return True
    else:
        return False



@RestControllerWithDepends()
class InfirmaryBusinessesDoctorInterimSchedulingController(IController):

    def business_login(self):
        pass
        # 注意需要同时的删除缓存记录信息，看看这个目前是否必须

        # 先查询当前的日期是否已经存在了排班的记录存在的，句不再继续添加

        checkinfo = Businesses.check_businesses_doctor_user_scheduling_info(
            appid=self.schema_param.appid,
            dc_number = self.schema_param.dc_number,
            si_number = self.schema_param.si_number,
            scheduling_dnotime = self.schema_param.scheduling_dnotime
        )
        if checkinfo:
            self.response_ok = False
            self.response_msg = '当前排班日期已存在排班数据了！'
            return None

        # 开始根据规律生成排班记录

        interval_time = self.schema_param.interval_time
        # if interval_time not in [10,20,30,40,50,60]:
        #     self.response_ok = False
        #     self.response_msg = '排班的间隔时间建议设置'
        #     return None

        interval_scheduling_stock = self.schema_param.interval_scheduling_stock
        appid = self.schema_param.appid
        si_number = self.schema_param.si_number
        dc_number = self.schema_param.dc_number

        print("添加怎么了？？22222222222sssssssss222222？222", self.schema_param.scheduling_ampm)

        if self.schema_param.scheduling_ampm=='am':
            if not self.schema_param.interval_am_sart and not self.schema_param.interval_am_end:
                self.response_ok = False
                self.response_msg = 'interval_am_sart 或 interval_am_end 参数不能为空'
                return None

        if self.schema_param.scheduling_ampm == 'pm':
            if not self.schema_param.interval_pm_sart and not self.schema_param.interval_pm_end:
                self.response_ok = False
                self.response_msg = 'interval_pm_sart 或 interval_pm_end 参数不能为空'
                return None


        if self.schema_param.scheduling_dnotime and not is_valid_time_format_riqi(self.schema_param.scheduling_dnotime):
            self.response_ok = False
            self.response_msg = '排班日期的格式不对，需要是符合：00-00-00的格式'
            return None

        if not is_valid_time_format(self.schema_param.interval_am_sart):
            self.response_ok = False
            self.response_msg = 'interval_am_sart-时间戳格式不对，需要是符合：00:00的格式'
            return None

        if self.schema_param.interval_am_end and not is_valid_time_format(self.schema_param.interval_am_end):
            self.response_ok = False
            self.response_msg = 'interval_am_end-时间戳格式不对，需要是符合：00:00的格式'
            return None

        if self.schema_param.interval_pm_sart and not is_valid_time_format(self.schema_param.interval_pm_sart):
            self.response_ok = False
            self.response_msg = 'interval_pm_sart-时间戳格式不对，需要是符合：00:00的格式'
            return None

        if self.schema_param.interval_pm_end and not is_valid_time_format(self.schema_param.interval_pm_end):
            self.response_ok = False
            self.response_msg = 'interval_pm_end-时间戳格式不对，需要是符合：00:00的格式'
            return None
        
        
        # 检测时间格式正确


        re_date = self.schema_param.scheduling_dnotime



        # ==============am
        interval_am_sart = self.schema_param.interval_am_sart
        interval_am_end = self.schema_param.interval_am_end

        # 开始的时间
        start_time = datetime.datetime.strptime(f'{re_date} {interval_am_sart}', '%Y-%m-%d %H:%M')
        # 结束时间
        end_time = datetime.datetime.strptime(f'{re_date} {interval_am_end}', '%Y-%m-%d %H:%M')
        # 切割后时间间隔数组
        time_array = generate_time_array_for_times(start_time, end_time, minutes=interval_time)

        weekday = start_time.weekday() + 1

        # 正常的时间里面值安排医生坐诊日期内的
        # 周一、周二、周五-----程杯医生的排班
        weday = weekdaystrftime(weekday)

        # 开始分配时间数据需
        result =None
        for tatmaps in time_array:


            print(f'{re_date} {tatmaps}:00')
            print(tatmaps)
            print(weday)

            # 设置 key避免多次的重复设置
            sync_redis_client = self.request.app.sync_redis
            stock_ismsl_s_make_key = f"ismsl_s_make:{appid}：{si_number}:{dc_number}:{re_date}:{re_date} {tatmaps}:00"
            stock_ismsl_s_make_value = sync_redis_client.get(stock_ismsl_s_make_key)
            # 如果没有设置过则标记开始标记已设置值
            print("添加怎么了？？22222222222222222？",self.schema_param.scheduling_ampm)
            if not stock_ismsl_s_make_value:
                sync_redis_client.set(stock_ismsl_s_make_key, 1, ex=60 * 60 * 24 * 40)
                # 然后执行生成排班的逻辑
                scheduling_index = random_helper.get_uuid()
                # 添加医生的排班的业务逻辑
                result =Businesses.add_businesses_doctor_user_scheduling_info(
                    appid=appid,
                    si_number=si_number,
                    dc_number=dc_number,
                    scheduling_index=scheduling_index,
                    scheduling_ampm=self.schema_param.scheduling_ampm,
                    scheduling_dnotime=re_date,
                    scheduling_status=1,
                    weekday=weday,
                    scheduling_tiemampmstr=tatmaps,
                    scheduling_stock=interval_scheduling_stock,
                    scheduling_tiempm=f'{re_date} {tatmaps}:00',
                )
                print("添加怎么了？？？",result)
                # 如果添加成功
                if result:
                    pass
                    # 设置缓存========
                    stock_key = f"dno:{dc_number}:"
                    # # 预扣库存数
                    dno_yukoustock = f"dno_yukoustock:{dc_number}:"
                    # 总库存数
                    curr_stock_key = f'{stock_key}{scheduling_index}'
                    # # 预扣库存数
                    curr_dno_yukoustock = f'{dno_yukoustock}{scheduling_index}'
                    # 从redis里面读取数据

                    curr_paiban_datatime = datetime.datetime.strptime(f'{re_date} {tatmaps}:00',
                                                                      '%Y-%m-%d %H:%M:%S')
                    today = time.strftime('%Y-%m-%d %H:%M', time.localtime(time.time()))
                    newdata_today = datetime.datetime.strptime(today.replace("-", ""),
                                                               "%Y%m%d %H:%M")  # 字符串转化为date形式
                    # 同步更新预扣库存redis的数据信息--
                    total_seconds = int(abs((newdata_today - (curr_paiban_datatime + datetime.timedelta(days=40))).total_seconds()))
                    # =======================
                    # 剩余预扣库存数
                    # 同步号源总数和预扣库存数
                    sync_redis_client.set(curr_stock_key, interval_scheduling_stock, ex=total_seconds)
                    # =======================
                    # 累计预扣库存数从0开始累计
                    sync_redis_client.set(curr_dno_yukoustock, 0, ex=total_seconds)
                    # =======================
                    # 设置改时段内就诊序号的reids-key值信息
                    dno_visit_num_key = f"dno_visit_num:{dc_number}:{scheduling_index}"
                    # 该只有效期是一个月
                    sync_redis_client.set(dno_visit_num_key, 0, ex=60 * 60 * 24 * 31)

        if result:
            self.response_msg = '临时排班添加成功'
        else:
            self.response_ok = False
            self.response_msg = '临时排班添加失败'
            return None


